package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Resource;

import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import org.springframework.beans.factory.annotation.Autowired;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.context.CuccServiceContext;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * @Classname LocalInstallAddressAttrHandler
 * @Description 处理装机地址的虚拟属性省市县控件，选择值后，将值回填至 省市县 三个属性
 * @Author zhang.song
 * @Date 2021-03-02 14:47
 */
public class LocalInstallAddressAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {

    @Resource
    private IUnicomRegionService unicomRegionService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;


    /**
     * 装机地址 省市默认值：操作人省市
     */
    @Override
    public void after(KiteAttr attr, KiteInst inst, AttrData data) {
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(KiteStringUtils.equalsAny(provinceCode,"48","49")){
            super.after(attr, inst, data);
            return;
        }
        // 订购、核查 操作，初始默认值
        if (KiteStringUtils.equalsAny(data.getServiceOfferId(), ServiceOfferConsts.SERVICE_OFFER_ORDER, LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)) {
            String filedName = attr.getFieldName();
            String productId = inst.getSpecId();

            List<String> filterJpwProdId = new ArrayList<>();
            List<String> filterJpwOfferId = new ArrayList<>();
            getJpwFilterOfferId(filterJpwProdId,filterJpwOfferId);
            if(filterJpwProdId.contains(productId) && KiteStringUtils.equalsAny(filedName, "kit0000224", "2_0000105")){
                int index = filterJpwProdId.indexOf(productId);
                String offerIds = filterJpwOfferId.get(index);
                if(KiteStringUtils.isNotEmpty(offerIds)){
                    KiteOfferInst kiteOfferInst = querySceneInstService.getMainOfferInst(data.getSceneInstId());
                    String offerId = kiteOfferInst.getOfferId();
                    String[] offerArr = offerIds.split(",");
                    List<String> offerList = Arrays.asList(offerArr);
                    if(!offerList.contains(offerId)){
                        // 政企精品网省际、省内，Z端没有默认值，本地有
                        super.after(attr, inst, data);
                        return;
                    }
                }
            }
            List<String> filterProdId = this.getFilterProdId();
            if (filterProdId.contains(productId) && KiteStringUtils.equalsAny(filedName, "kit0000224", "2_0000105")) {
                // 省际、省内、国际，Z端没有默认值
                super.after(attr, inst, data);
                return;
            }
            List<String> gj = this.getFilterGJProdId();
            if (gj.contains(productId) && KiteStringUtils.equalsAny(filedName, "2_0000209")) {
                // 国际长途穿境和纯境外A端没有默认值
                super.after(attr, inst, data);
                return;
            }
            // 国际互联网没有默认值
            KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(data.getSceneInstId());
            String offerId = Optional.ofNullable(querySceneInstService.getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId())).map(KiteOfferInst::getOfferId).orElse(null);
            if("50040853".equals(offerId)) {
                super.after(attr, inst, data);
                return;
            }

            String value = attr.getValue();
            if (KiteStringUtils.isEmpty(value)) {
                UserInfo userInfo = ContextUtil.getLoginInfo().getUserInfo();
                if (userInfo != null) {
                    String provinceId = userInfo.getPostProvinceNbr();
                    String cityId = userInfo.getPostLanId();
                    if (KiteStringUtils.isNotEmpty(provinceId)) {
                        super.set(attr, inst, provinceId + (KiteStringUtils.isEmpty(cityId) ? "" : ("," + cityId)), data);
                    }
                }
            }

        }
        super.after(attr, inst, data);
    }

    /**
     * 获取页面展示名称
     *
     * @param attr  实例属性入参
     * @param inst  当前操作的实例对象
     * @param value 设置的值
     * @param data  属性处理入参，可以根据需要传入需要的业务数据
     * @return 属性页面展示名称
     */
    @Override
    public String getValueDesc(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        if (KiteStringUtils.isEmpty(value)) {
            return value;
        }
        if (KiteStringUtils.equalsAny(value, ",", ",,")) {
            return "";
        }

        List<List<UnicomRegion>> lists = new ArrayList<>();
        List<UnicomRegion> unicomRegions = CuccServiceContext.getRegions(inst.getSpecId());
        if (KiteListUtils.isEmpty(unicomRegions)) {
            unicomRegions = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(inst.getSpecId()));
            CuccServiceContext.setRegions(inst.getSpecId(), unicomRegions);
        }
        lists.add(unicomRegions);

        String key = KiteStringUtils.concatWithNnderline("RegionCode", value);
        List<List<UnicomRegion>> innerUnicomRegions = CuccServiceContext.getInnerRegions(key);
        if (KiteListUtils.isEmpty(innerUnicomRegions)) {
            innerUnicomRegions = unicomRegionService.subRegionMultiFromPlatformByRegionCode(value);
            CuccServiceContext.setInnerRegions(key, innerUnicomRegions);
        }
        lists.addAll(innerUnicomRegions);

        //lists.add(unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(inst.getSpecId())));
        //lists.addAll(unicomRegionService.subRegionMultiFromPlatformByRegionCode(value));
        String[] regionCodes = KiteStringUtils.split(value, SymbolConsts.COMMA);
        List<String> regionNames = new ArrayList<>();
        for (int i = 0; i < regionCodes.length; i++) {
            String currentRegionCode = regionCodes[i];
            String regionName = lists.get(i).stream()
                .filter(unicomRegion -> currentRegionCode.equals(unicomRegion.getRegionCode())).findAny()
                .map(UnicomRegion::getRegionName).orElse("");
            regionNames.add(regionName);
        }

//        List<String> regionNames = Arrays.stream(regionCodes).map(s -> {
//            UnicomRegion region = unicomRegionService.getRegion(s);
//            return Objects.nonNull(region) ? region.getRegionName() : "";
//        }).collect(Collectors.toList());
        return KiteStringUtils.join(regionNames, SymbolConsts.HYPHEN);
    }

    @Override
    public void onShow(KiteAttr attr, KiteInst inst, AttrData data) {
        super.onShow(attr, inst, data);

        String cateId = CuccPosServiceUtils.getCateId(data.getSceneInstId(), data.getCustId());
        // SDWAN可以编辑，跳过
        String nodeCode = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "nodeCode");
        if("BatchInput".equals(nodeCode)){
            return;
        }
        if(!KiteStringUtils.equalsAny(cateId, "2101120", "2004141")) {
            // 互联网类产品,装机地址属性在订单归集后的环节不允许再编辑
            IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
            IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);

            // app甩单补录、资源核查补录情况，可以编辑
            String renderOrderType = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "renderOrderType");
            if (!KiteStringUtils.isEmpty(nodeCode) && !KiteStringUtils.isEqual(renderOrderType, "orderRejection")) {
                attr.setIsEdit(KeyConsts.IFTRUE_F);
                operateSceneInstService
                    .setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), attr);
            }
        }
    }

    private List<String> getFilterProdId() {
        List<String> filterProdIds = new ArrayList<>();
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("SNCT_PROD_ID", ProdCateUtil.YTW_CODE, ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("SJCT_PROD_ID", ProdCateUtil.YTW_CODE, ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("GJKJ_PROD_ID", ProdCateUtil.YTW_CODE, ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("GJCJ_PROD_ID", ProdCateUtil.YTW_CODE, ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("GJCJW_PROD_ID", ProdCateUtil.YTW_CODE,ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode(ProdCateUtil.MV_CODE)).ifPresent(filterProdIds::addAll);
         return filterProdIds;
    }
    private List<String> getFilterGJProdId() {
        List<String> filterProdIds = new ArrayList<>();
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("GJCJ_PROD_ID", ProdCateUtil.YTW_CODE, ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode("GJCJW_PROD_ID", ProdCateUtil.YTW_CODE,ProdCateUtil.SDH_CODE)).ifPresent(filterProdIds::addAll);
        Optional.ofNullable(ProdCateUtil.getProdIdByPCode(ProdCateUtil.MV_CODE)).ifPresent(filterProdIds::addAll);
         return filterProdIds;
    }

    private void getJpwFilterOfferId(List<String> prodIds, List <String> offerIds) {
        List<DcPublic> dcPublicList = DcPublicCache.get("202109210001");
        if (Objects.nonNull(dcPublicList)) {
            dcPublicList.forEach(dcPublic -> {
                prodIds.add(dcPublic.getPkey());
                offerIds.add(dcPublic.getPcode());
            });
        }
    }
}
